# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import models, fields, api, _
from odoo.tools.misc import format_date
from datetime import datetime, timedelta
from odoo.addons.web.controllers.main import clean_action
from odoo.tools import float_is_zero
import logging
_logger = logging.getLogger(__name__)


class report_account_cash_flow(models.AbstractModel):
    _name = "account.cash.flow"
    _description = "Account Cash Flow"
    _inherit = "account.report"

    filter_date = {'date_from': '', 'date_to': '', 'filter': 'this_month'}
    filter_cash_basis = False
    filter_all_entries = False
    filter_journals = True
    filter_analytic = True
    filter_unfold_all = False

    # TO BE OVERWRITTEN
    def _get_columns_name_hierarchy(self, options):
        return []

    # TO BE OVERWRITTEN

    def _get_templates(self):
        templates = super(report_account_cash_flow,
                          self)._get_templates()
        templates['main_template'] = 'l10n_cn_standard_lastest.line_template_cash_flow_report'
        templates['line_template'] = 'account_reports.line_template_general_ledger_report'
        return templates

    # TO BE OVERWRITTEN
    def _get_columns_name(self, options):
        return [{'name': ''},
                {'name': _("科目")},
                {'name': _("Date"), 'class': 'date'},
                {'name': _("摘要")},
                {'name': _("Partner")},
                {'name': _("Debit"), 'class': 'number'},
                {'name': _("贷方"), 'class': 'number'},
                {'name': _("Balance"), 'class': 'number'}]

    # TO BE OVERWRITTEN

    def _get_report_name(self):
        return _('现金流量表')

    # TO BE OVERWRITTEN
    # 只选项科目是银行或现金类型
    def _get_lines(self, options, line_id=None):
        _logger.info(options)
        _logger.info(line_id)
        line_id_param = line_id
        line_id = line_id and int(line_id.split('_')[1]) or None
        lines = []
        # 点击item
        if(line_id):
            tem = self.env['account.analytic.tag'].sudo().search(
                [('id', '=', line_id)])
            sql = "SELECT cash_flow_tag,SUM(debit),SUM(credit),SUM(balance) FROM account_move_line as aml left join account_account as account on (aml.account_id = account.id)  WHERE account.user_type_id = 3 and aml.company_id ="+ str(self.env.user.company_id.id) +" AND aml.cash_flow_tag = " + str(line_id) + "  AND aml.date >='" + \
                options['date']['date_from'] + \
                "' AND aml.date <='" + \
                options['date']['date_to']+"' GROUP BY aml.cash_flow_tag"
            self.env.cr.execute(sql)
            results = self.env.cr.fetchall()
            first = {
                'id': 'tag_'+str(line_id),
                'name': tem[0].name,
                'title_hover': tem[0].name,
                'columns': [{'name': ''}, {
                    'name': results[0][1]
                }, {
                    'name': results[0][2]
                }, {
                    'name': results[0][3]
                }],
                'level': 2,
                'unfoldable': True,
                'unfolded': True,
                'colspan': 4
            }
            lines.append(first)
            amls = self.env['account.move.line'].sudo().search([('company_id','=',self.env.user.company_id.id),('cash_flow_tag', '=', line_id), (
                'date', '>=', options['date']['date_from']), ('date', '<=', options['date']['date_to']), ('account_id.user_type_id', '=', 3)])
            for aml in amls:
                tem = {
                    'id': aml.id,
                    'caret_options': 'account.move',
                    'class': 'top-vertical-align',
                    'parent_id': line_id_param,
                    'name': aml.move_id.name,
                    'columns': [{'name': aml.account_id.name}, {
                        'name': aml.date,
                    }, {
                        'name': aml.name,
                        'class': 'whitespace_print',
                        'title': aml.name
                    }, {
                        'name': aml.partner_id.name,
                        'class': 'whitespace_print',
                        'title': aml.partner_id.name
                    },  {
                        'name': aml.debit
                    }, {
                        'name': aml.credit
                    }, {
                        'name': aml.balance
                    }],
                    'level': 4
                }
                lines.append(tem)
            return lines

        # 第一次进入
        i = 1
        while i < 24:
            _ref = 'l10n_cn_standard_lastest.analytic_tag' + str(i)
            lines.append({
                'id': 'tag_'+str(self.env.ref(_ref).id),
                'name': self.env.ref(_ref).name,
                'title_hover': self.env.ref(_ref).name,
                'columns': [
                    {
                        'name': ''
                    },
                    {
                        'name': ''
                    }, {
                        'name': ''
                    }, {
                        'name': ''
                    }],
                'level': 2,
                'unfoldable': False,
                'unfolded': None,
                'colspan': 4
            })
            i = i + 1
        # self.env['account.move.line'].sudo().search([('cash_flow_tag','=',),()])
        sql = "SELECT cash_flow_tag,SUM(debit),SUM(credit),SUM(balance) FROM account_move_line as aml left join account_account as account on (aml.account_id = account.id) where aml.company_id = "+ str(self.env.user.company_id.id) +" and account.user_type_id = 3 and aml.date >='" + \
            options['date']['date_from'] + \
            "' AND aml.date <='" + \
            options['date']['date_to']+"' GROUP BY aml.cash_flow_tag"
        self.env.cr.execute(sql)
        results = self.env.cr.fetchall()
        # self.env.cr.close()
        for result in results:
            if result[0]:
                # _logger.info(result[0])
                # _logger.info(type(result[0]))
                for line in lines:
                    line_id = int(line['id'].split('_')[1])
                    if line_id == result[0]:
                        line['columns'][1]['name'] = result[1]
                        line['columns'][2]['name'] = result[2]
                        line['columns'][3]['name'] = result[3]
                        line['unfoldable'] = True
        return lines
